<!-- eslint-disable no-console -->
<script lang="ts" setup>
import type { DictApi, QctemplateApi, ToolTypeApi } from '#/api';

import { reactive, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

// import { el-tab-pane, ElTabs } from 'element-plus';
import { useVbenForm } from '#/adapter/form';
import {
  addQctemplate,
  DictResp,
  getQctemplateCode,
  updateQctemplate,
} from '#/api';

import tableTemplateindex from './modules/table-templateindex.vue';

const emit = defineEmits(['success']);

// const templateData = ref();
// const mes_index_type = ref();
const formdata = ref<QctemplateApi.Row>();
const mes_qc_detail_type = reactive<DictApi.SelectOption[]>([]);
const sys_yes_no = reactive<DictApi.SelectOption[]>([]);
DictResp(['mes_qc_detail_type', 'sys_yes_no']).then((res) => {
  console.log(res);

  // 将两个数组合并
  if (res.mes_qc_detail_type) {
    mes_qc_detail_type.push(...res.mes_qc_detail_type);
  }
  if (res.sys_yes_no) {
    sys_yes_no.push(...res.sys_yes_no);
  }
});

const [Modal, modalApi] = useVbenModal({
  closeOnClickModal: false,
  async onConfirm() {
    const { valid } = await baseFormApi.validate();
    if (valid) {
      modalApi.lock();

      let data;
      await baseFormApi.getValues().then((res) => {
        console.log(res);
        data = res;
      });
      try {
        await (formdata.value?.templateId
          ? updateQctemplate(data!)
          : addQctemplate(data!));
        emit('success', formdata.value?.templateId ? '修改成功' : '新增成功');
        modalApi.close();
      } finally {
        modalApi.lock(false);
      }
    }
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const data = modalApi.getData();
      if (data) {
        formdata.value = data.row;
        console.log(formdata.value);
        baseFormApi.setValues(formdata.value as any);
      }
    }
  },
});

const switchValue = ref('');
const [BaseForm, baseFormApi] = useVbenForm({
  // 所有表单项共用，可单独在表单内覆盖
  showDefaultActions: false,
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  // 提交函数
  handleSubmit: onSubmit,
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      rules: 'required',
      dependencies: {
        show: false,
        triggerFields: ['templateId'],
      },
      fieldName: 'templateId',
      label: 'Id',
    },
    {
      // 组件需要在 #/adapter.ts内注册，并加上类型
      component: 'Input',
      rules: 'required',
      // 对应组件的参数
      componentProps: {
        placeholder: '请输入方案编码',
      },
      // 字段名
      fieldName: 'templateCode',
      // 界面显示的label
      label: '方案编号',
      formItemClass: 'col-span-4',
      dependencies: {
        triggerFields: ['switch'],
        trigger(values) {
          values.templateCode = switchValue;
        },
      },
    },
    {
      component: 'Switch',
      fieldName: 'switch',
      label: '自动生成',
      formItemClass: 'col-start-5 col-span-2',
      labelWidth: 100,
      componentProps: {
        defaultValue: 0,
        onChange: (e: boolean) => {
          if (e) {
            getQctemplateCode().then((res) => {
              console.log(res);
              switchValue.value = res.data;
            });
          } else {
            switchValue.value = '';
          }
        },
      },
    },
    {
      component: 'Input',
      rules: 'required',
      componentProps: {
        placeholder: '请输入方案名称',
      },
      fieldName: 'templateName',
      label: '方案名称',
      formItemClass: 'col-span-5',
    },
    {
      component: 'CheckboxGroup',
      rules: 'required',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: mes_qc_detail_type,
        placeholder: '请选择',
        showSearch: true,
      },
      fieldName: 'qcTypesParam',
      label: '业务类型',
      formItemClass: 'col-span-8',
    },
    {
      component: 'RadioGroup',
      componentProps: {
        options: sys_yes_no,
      },
      fieldName: 'enableFlag',
      label: '是否启用',
      formItemClass: 'col-span-4',
    },
    {
      component: 'Textarea',

      componentProps: {
        placeholder: '请输入内容',
      },
      formItemClass: 'col-span-12',
      fieldName: 'remark',
      label: '备注',
    },
  ],
  wrapperClass: 'grid grid-cols-12',
});

function onSubmit(values: Record<string, any>) {
  console.log(values);

  modalApi.close();
}

// 存储选中行的响应式变量
const selectedRows = ref<ToolTypeApi.Row[]>([]);
const initData = {
  toolTypeId: null,
  toolTypeCode: '',
  toolTypeName: '',
  codeFlag: 'Y',
  maintenType: null,
  maintenPeriod: null,
  remark: '',
};
selectedRows.value = [initData];
</script>
<template>
  <Modal class="w-5/6">
    <div>
      <BaseForm />
      <div v-if="formdata?.templateId">
        <tableTemplateindex :template="formdata?.templateId" />
      </div>
    </div>
  </Modal>
</template>
